#!/usr/bin/env python
"""
Acorn-SDR (A Collaboration of Radio Nodes)
(c) Bob Cowdery (G3UKB) 2009

File: softrock_service.py
Date: January 2009

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

The author can be reached by email at

bob@g3ukb.co.uk

========================================================================
Module Description:

The softrock hw service.

"""

#-----------------------------------------------------------------------
# System imports
import sys
import os
from time import sleep
import Ice, IceStorm

# Application imports
import softrock_controller
import ice_helpers
import utils

# Import the Ice interface definitions
import AcornLifeCycle
import AcornRxUpdate
import AcornRxControl
import AcornPersist

#===============================================================================
# Ice life-cycle events for the controller
class LifeCycleI(AcornLifeCycle.LifeCycle):
    
    #---------------------------------------------------------------------------   
    def __init__(self, service, softrock_impl):
        self.softrock_impl = softrock_impl
        self.service = service
      
    #---------------------------------------------------------------------------
    def start(self, current=None):
        pass
     
    #---------------------------------------------------------------------------   
    def stop(self, current=None):
        pass
    
    #---------------------------------------------------------------------------    
    def terminate(self, current=None):
        self.service.terminate()
        
#===============================================================================
# Ice command events for the HW Controller
class RxControlI(AcornRxControl.RxControl):
    
    #---------------------------------------------------------------------------   
    def __init__(self, service, softrock_impl):
      self.softrock_impl = softrock_impl
      self.service = service
        
    #---------------------------------------------------------------------------   
    def freqSet(self, freq, current=None):
        self.softrock_impl.freq_set(freq)
        
    #---------------------------------------------------------------------------   
    def freqInc(self, inc, current=None):
        self.softrock_impl.freq_inc(inc)
        
#===============================================================================
class SoftrockService(Ice.Application):

    def __init__(self):
        self.close = False
    
    #---------------------------------------------------------------------------
    # Run the app
    def run(self, args):
       
        #-----------------------------------------------------------------------
        # persist interface
        persist = ice_helpers.get_interface('Softrock Service', self.communicator, AcornPersist.PersistPrx, 'Persist.Proxy')        
        # Get config data
        
        #-----------------------------------------------------------------------
        # Event names used here
        publish_to_rx_updates = 'rx_update_events'
        subscribe_to_rx_control = 'rx_control_events'
        subscribe_to_lc = 'life_cycle_events'
  
        #-----------------------------------------------------------------------
        # This is the same for both publishers and subscribers
        # Get the IceStorm topic manager interface
        manager = ice_helpers.get_topic_manager('Softrock Service', self.communicator)
        
        # Retrieve the subscriber topic
        rx_control_topic = ice_helpers.get_topic('Softrock Service', manager, subscribe_to_rx_control)
        life_cycle_topic = ice_helpers.get_topic('Softrock Service', manager, subscribe_to_lc)
        
        # Retrieve the publisher topic
        rx_publisher_topic = ice_helpers.get_topic('Softrock Service', manager, publish_to_rx_updates)
  
        #-----------------------------------------------------------------------
        # Publisher side
        # Get the topic's publisher object, and create a hw proxy with
        # the mode specified as an argument of this application.
        #
        publisher = publisher_topic.getPublisher();
        publisher = publisher.ice_oneway();        
        rx_update_publisher = AcornRxUpdate.RxUpdatePrx.uncheckedCast(publisher)
        
        #-----------------------------------------------------------------------
        # Initialise the Controller as its needed for the adapter and requires the update publisher
        softrock_impl = softrock_controller.SoftrockController(rx_update_publisher)
        
        #-----------------------------------------------------------------------
        # Subscriber side
        # Create an adapter for the subscriber   
        adapter_1 = self.communicator().createObjectAdapter("RxControl.Subscriber")
        subId_1 = Ice.Identity()
        subId_1.name = Ice.generateUUID()      
        # Add the update interface
        subscriber_1 = adapter_1.add(RxControlI(self, softrock_impl), subId_1)
        # Subscribe to the topic - set up proxy
        ice_helpers.subscribe('Softrock Service', rx_control_topic, subscriber_1, id)
        # Now we can receive callbacks   
        adapter_1.activate()
        
        adapter_2 = self.communicator().createObjectAdapter("LifeCycle.Subscriber")
        subId_2 = Ice.Identity()
        subId_2.name = Ice.generateUUID()        
        # Add the update interface
        subscriber_2 = adapter_2.add(LifeCycleI(self, softrock_impl), subId_2)
        # Subscribe to the topic - set up proxy
        ice_helpers.subscribe('Softrock Service', life_cycle_topic, subscriber_2, id)
        # Now we can receive callbacks   
        adapter_2.activate()
        
        print 'Acorn-SDR (Softrock Service) running..'
        
        #-----------------------------------------------------------------------
        # Wait for closedown
        while not self.close:
            # Idle loop for doing any other work
            sleep(1)

        # Unsubscribe all subscribed objects.
        # Causes issues at the moment
        #rx_control_topic.unsubscribe(subscriber_1)
        #life_cycle_topic.unsubscribe(subscriber_2)
    
    #---------------------------------------------------------------------------
    # Terminate
    def terminate(self):
        self.close = True
        
#===============================================================================
#===============================================================================
# Start from the command line
if __name__ == "__main__":
   
  app = SoftrockService()
  app.main(sys.argv, sys.argv[1])
  
  # Announce we are going 
  print 'Acorn-SDR (Softrock Service) closing..'

    